package com.yunqiao.api.controller;

import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunqiao.api.utils.JwtUtils;
import com.yunqiao.common.exception.CustomApiException;
import com.yunqiao.common.utils.ApiResponse;
import com.yunqiao.common.validator.ValidatorUtils;
import com.yunqiao.service.api.AppAccountService;
import com.yunqiao.service.api.SysSmscodeService;
import com.yunqiao.service.api.UserService;
import com.yunqiao.service.api.entity.UserEntity;
import com.yunqiao.service.api.form.ForgetPasswordForm;
import com.yunqiao.service.api.form.LoginForm;
import com.yunqiao.service.api.form.RegisterForm;
import com.yunqiao.service.api.vo.CheckCodeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * 注册
 *
 * @author Crocutax
 * @email wangxw725@163.com
 * @date 2017-03-26 17:27
 */
@RestController
@RequestMapping("/api/auth")
@Api(tags = "AppAccountController", description = "APP登陆注册板块")
public class AppAccountController {

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private AppAccountService appAccountService;
    @Autowired
    private SysSmscodeService sysSmscodeService;
    @Resource
    private TimedCache<String, String> timedCache;
    @Resource
    private UserService userService;
    @PostMapping("userRegister")
    @ApiOperation("注册(两端通用)")
    public ApiResponse register(@RequestBody RegisterForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form);
        Long userId = appAccountService.register(form);
        //生成token
        String token = jwtUtils.generateToken(form.getRoleType(),userId);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("userId", userId);
        return new ApiResponse(map);
    }

    /**
     * 货主登录
     */
    @PostMapping("userLogin")
    @ApiOperation("登录(两端通用)")
    public ApiResponse<Map> login(@RequestBody LoginForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form);
        //用户登录
        UserEntity userEntity = appAccountService.login(form);
        //生成token
        String token = jwtUtils.generateToken(form.getRoleType(),userEntity.getId());

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("userId", userEntity.getId());
        map.put("isSetDetails", StrUtil.isNotBlank(userEntity.getName()));
        if(userEntity.getRoleType()==2){
            map.put("carType",userEntity.getCarTypeId());
            map.put("driverState",userEntity.getDriverState());
        }
        return new ApiResponse<Map>(map);
    }

    /**
     * 绑定微信
     * @param code
     * @return
     */
    @PostMapping("/v1/bingdangWx")
    @ApiOperation("绑定微信号")
    public ApiResponse bingdingPhonev1(@RequestBody CheckCodeVo code){
        //BeanUtils.copyProperties(code);
        if(timedCache.get(code.getPhone()).equals(code.getCode())){
            Map<String,Object> map=new HashMap<>();
            UserEntity user= userService.getOne(new QueryWrapper<UserEntity>().eq("phone",code.getPhone()).eq("role_type",1));
            if(user!=null&&code.getUserId()==null){
                UserEntity user1=new UserEntity();
                user1.setWxCloudOpenid(code.getWxCloudOpenid());
                user1.setId(user.getId());
                userService.updateById(user1);
                String token = jwtUtils.generateToken(1,user.getId());
                map.put("token", token);
                map.put("expire", jwtUtils.getExpire());
                map.put("userId", user.getId());
                map.put("name", user.getName());
                map.put("isSetDetails", StrUtil.isNotBlank(user.getName()));
                map.put("phone",user.getPhone());
                return new ApiResponse(map);
            }else if(code.getUserId()!=null){
                user=new UserEntity();
                user.setId(code.getUserId());
                user.setPhone(code.getPhone());
                userService.updateById(user);
                String token = jwtUtils.generateToken(1,user.getId());
                map.put("token", token);
                map.put("expire", jwtUtils.getExpire());
                map.put("userId", user.getId());
                map.put("phone",user.getPhone());
                return new ApiResponse(map);
            }else {
                UserEntity newUser=new UserEntity();
                try {
                    newUser.setProvince(code.getProvince());
                    newUser.setWxCloudOpenid(code.getWxCloudOpenid());
                    newUser.setCity(code.getCity());
                    newUser.setSex(code.getSex());
                    newUser.setAvatar(code.getAvatar());
                    newUser.setName(code.getName());
                    newUser.setRoleType(1);
                    newUser.setPhone(code.getPhone());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                userService.save(newUser);
                String token = jwtUtils.generateToken(1,newUser.getId());

                map.put("token", token);
                map.put("expire", jwtUtils.getExpire());
                map.put("userId", newUser.getId());
                map.put("name", newUser.getName());
                map.put("isSetDetails", StrUtil.isNotBlank(newUser.getName()));
                map.put("phone",newUser.getPhone());
                return new ApiResponse(map);
            }
        }else {
            throw new CustomApiException("验证码错误");
        }
    }
    /**
     * 绑定微信
     * @param code
     * @return
     */
    @PostMapping("bingdangWx")
    @ApiOperation("绑定微信号")
    public ApiResponse bingdingPhone(@RequestBody CheckCodeVo code){
        if(timedCache.get(code.getPhone()).equals(code.getCode())){
            UserEntity user= new UserEntity();
            user.setId(code.getUserId());
            user.setPhone(code.getPhone());
            userService.updateById(user);
        }else {
            throw new CustomApiException("验证码错误");
        }
        return new ApiResponse();
    }
    /**
     * 绑定支付宝
     * @param code
     * @return
     */
    @PostMapping("bingdangAli")
    @ApiOperation("绑定支付宝")
    public ApiResponse bingdingAly(@RequestBody CheckCodeVo code){
        if(timedCache.get(code.getPhone()).equals(code.getCode())){
            Map<String,Object> map=new HashMap<>();
            UserEntity user= userService.getOne(new QueryWrapper<UserEntity>().eq("phone",code.getPhone()).eq("role_type",1));
            if(user!=null&&code.getUserId()==null){
                UserEntity user1=new UserEntity();
                user1.setAliCloudOpenid(code.getAliCloudOpenid());
                user1.setId(user.getId());
                userService.updateById(user1);
                String token = jwtUtils.generateToken(1,user.getId());
                map.put("token", token);
                map.put("expire", jwtUtils.getExpire());
                map.put("userId", user.getId());
                map.put("name", user.getName());
                map.put("isSetDetails", StrUtil.isNotBlank(user.getName()));
                map.put("phone",user.getPhone());
                return new ApiResponse(map);
            }else if(code.getUserId()!=null){
                user=userService.getById(code.getUserId());
                String token = jwtUtils.generateToken(1,user.getId());
                map.put("token", token);
                map.put("expire", jwtUtils.getExpire());
                map.put("userId", user.getId());
                map.put("name", user.getName());
                map.put("isSetDetails", StrUtil.isNotBlank(user.getName()));
                map.put("phone",user.getPhone());
                UserEntity newuser=new UserEntity();
                newuser.setId(code.getUserId());
                newuser.setPhone(code.getPhone());
                userService.updateById(newuser);
                return new ApiResponse(map);
            }else {
                user=new UserEntity();
                user.setProvince(code.getProvince());
                user.setAliCloudOpenid(code.getAliCloudOpenid());
                user.setCity(code.getCity());
                user.setSex(code.getGender().equals("m")?1:2);
                user.setAvatar(code.getAvatar());
                user.setName(code.getNickName());
                user.setRoleType(1);
                user.setPhone(code.getPhone());
                userService.save(user);
                String token = jwtUtils.generateToken(1,user.getId());
                map.put("token", token);
                map.put("expire", jwtUtils.getExpire());
                map.put("userId", user.getId());
                map.put("name", user.getName());
                map.put("isSetDetails", StrUtil.isNotBlank(user.getName()));
                map.put("phone",user.getPhone());
                return new ApiResponse(map);
            }

        }else {
            throw new CustomApiException("验证码错误");
        }
    }
    /**
     * 忘记密码
     */
    @PostMapping("forgetPassword")
    @ApiOperation("忘记密码(两端通用)")
    public ApiResponse<Map> forgetPassword(@RequestBody ForgetPasswordForm forgetPasswordForm) {
        //表单校验
        ValidatorUtils.validateEntity(forgetPasswordForm);
        appAccountService.forgerPassword(forgetPasswordForm);
        return new ApiResponse<>();
    }

    @GetMapping("getSmsCode")
    @ApiOperation("获取短信验证码")
    @ApiImplicitParam(name = "phone", value = "电话号码", required = true)
    public ApiResponse<Map> getSmsCode(String phone) throws Exception {
        if (phone == null) {
            throw new CustomApiException("手机号不能为空");
        }
        sysSmscodeService.sendSms(phone);
        return new ApiResponse<>();
    }
}
